import React, {PropTypes} from "react";
import {connect} from "react-redux";
import {fetchPosts, reset} from "../../actions";
import {Link} from "react-router";
import Swiper from "react-id-swiper";
import cookie from "react-cookie";

import GoodsConfig from "../../components/GoodsConfig";
import DetailMenu from "../../components/DetailMenu";
import BrandRate from "../../components/BrandRate";
import {login} from "../../utils/native_app";


class goodsDetail extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            isShow: false,
            item: {},
            buySpecifiedNo: 0,
            buySpecifiedName: '',
            buyNumber: 1,
            isShowBrandRate: false,
            shoppingCartCount: 0
        }
    }

    componentWillMount() {
        document.title = "详情";
    }

    componentDidMount() {
        const header = {"X-Client-ID": '123456'};
        const params = this.props.location.query;
        this.props.dispatch(reset("goodsDetail"));
        this.props.dispatch(fetchPosts("goodsDetail", header, params));
    }

    componentWillReceiveProps(nextProps) {
        let shoppingCartCount = this.getShoppingCartAccount();
        if (nextProps.GoodsInfo.errorCode === 0) {
            this.setState({
                loading: false,
                item: nextProps.GoodsInfo.data.goodsDetailVo,
                shoppingCartCount: shoppingCartCount
            })
        }
    }

    render() {
        if (this.state.loading) {
            return (<div className="loading"><span>loading</span></div>)
        } else {
            const {GoodsInfo, Config} = this.props;
            const params = {
                pagination: '.swiper-pagination',
                paginationType: 'fraction',
                loop: true,
                autoplay: 5000
            }
            const {goodsDetailVo} = GoodsInfo.data;
            return (
                <div>
                    <GoodsConfig
                        show={this.state.isShow}
                        item={this.state.item}
                        config={Config}
                        closed={() => this.setState({isShow: false})}
                        join={this.join.bind(this)}
                        setSpecificationNo={this.setSpecification.bind(this)}
                        setNumber={this.setBuyNumber.bind(this)}
                    />
                    <BrandRate
                        show={this.state.isShowBrandRate}
                        productCode={goodsDetailVo.productCode}
                        brand={goodsDetailVo.brand}
                        taxRateDesc={goodsDetailVo.taxRateDesc}
                        closed={() => this.setState({isShowBrandRate: false})}
                    />
                    <div>
                        <Swiper {...params} >
                            {goodsDetailVo.image.split(",").map((item) => (
                                <div key={item} className="inforHeader">
                                    <img src={item}/>
                                </div>
                            ))
                            }
                        </Swiper>
                    </div>

                    <div>
                        <div className="goods-detail-name">{goodsDetailVo.name}</div>
                        <div className="goods-detail-price">¥{goodsDetailVo.price}<s>¥{goodsDetailVo.bazaarPrice}</s>
                        </div>
                        <div className="goods-detail-product-area">{goodsDetailVo.producingArea}</div>
                    </div>

                    <div className="infoList">
                        <ul>
                            <li>
                                <Link onClick={this.join.bind(this, goodsDetailVo)}>规格数量选择</Link>
                            </li>
                            <li>
                                优惠:包邮
                            </li>
                            <li>
                                综合税:包税
                            </li>
                            <li>
                                <Link
                                    onClick={this.popupBrandRateInfoWindow.bind(this, goodsDetailVo)}>货品编号,品牌,税率</Link>
                            </li>
                        </ul>
                    </div>
                    <div className="goods-detail-images-title">
                        商品详情
                    </div>
                    <div className="goods-detail-images">
                        <ul>
                            {
                                goodsDetailVo.detailsInfo.split(",").map((item, index) => {
                                    return (
                                        <li>
                                            <img src={item} key={index}/>
                                        </li>
                                    );
                                })
                            }
                        </ul>
                    </div>

                    <DetailMenu addToShoppingCar={this.addToShoppingCar.bind(this)}
                                toBuy={this.buy.bind(this)}
                                shoppingCartCount={this.state.shoppingCartCount}
                                item={goodsDetailVo}
                    />
                </div>
            )
        }

    }

    join(item) {
        //弹出购买框
        const header = {"X-Client-ID": '123456'};
        const params = {
            "categoryCode": item.categoryCode,
            "goodsNo": item.goodsNo,
            "specificationNo": item.specificationNo
        }
        this.setState({
            isShow: true
        })
        this.props.dispatch(fetchPosts("goodsConfig", header, params));
    }

    popupBrandRateInfoWindow() {
        console.log("popupBrandRateInfoWindow");
        //弹出品牌，税率框
        this.setState({
            isShowBrandRate: true
        });
        //this.props.dispatch(reset("showBrandRate"));
    }

    setSpecification(specificationNo, specificationName) {
        this.setState({buySpecifiedNo: specificationNo});
        this.setState({buySpecifiedName: specificationName});
    }

    setBuyNumber(buyNumber) {
        this.setState({buyNumber: buyNumber});
    }

    addToShoppingCar(item) {
        if (this.state.buySpecifiedNo == 0) {
            this.join(item);
            return;
        }

        let existGoods = false;
        let shoppingCarItemList = cookie.load("shoppingCarItemList") || [];
        shoppingCarItemList.map((item) => {
            if (item.categoryCode == this.state.item.categoryCode && item.goodsNo == this.state.item.goodsNo
                && item.specificationNo == this.state.buySpecifiedNo) {
                item.buyNumber = item.buyNumber + this.state.buyNumber;
                existGoods = true
            }
        })

        if (!existGoods) {
            let shoppingCarItem = {
                categoryCode: this.state.item.categoryCode,
                goodsNo: this.state.item.goodsNo,
                image: this.state.item.image,
                name: this.state.item.name,
                secondName: this.state.item.secondName,
                bazaarPrice: this.state.item.bazaarPrice,
                price: this.state.item.price,
                specificationNo: this.state.buySpecifiedNo,
                specificationName: this.state.buySpecifiedName,
                buyNumber: this.state.buyNumber,
                tradeType: this.state.item.tradeType,
                isChecked: false
            };
            shoppingCarItemList.push(shoppingCarItem);
        }
        cookie.save("shoppingCarItemList", shoppingCarItemList);
        this.setState({shoppingCartCount: this.getShoppingCartAccount()});
        alert("成功加入购物车");
    }


    buy(item) {//立即购买
        if (this.state.buySpecifiedNo == 0) {
            this.join(item);
            return;
        }
        const shoppingItemList = [{
            categoryCode: this.state.item.categoryCode,
            goodsNo: this.state.item.goodsNo,
            image: this.state.item.image,
            name: this.state.item.name,
            secondName: this.state.item.secondName,
            bazaarPrice: this.state.item.bazaarPrice,
            price: this.state.item.price,
            specificationNo: this.state.buySpecifiedNo,
            specificationName: this.state.buySpecifiedName,
            buyNumber: this.state.buyNumber,
            tradeType: this.state.item.tradeType
        }];
        cookie.save("shoppingItemList", shoppingItemList);
        login("/#/mall/orderConfirm?isFromShoppingCar=0");
    }

    getShoppingCartAccount() {
        let shoppingCartCount = 0;
        let shoppingCarItemList = cookie.load("shoppingCarItemList") || [];
        if (shoppingCarItemList.length > 0) {
            shoppingCarItemList.map((item) => {
                shoppingCartCount += item.buyNumber;
            });
        }
        return shoppingCartCount;
    }

}

goodsDetail.propTypes = {
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
}
goodsDetail.contextTypes = {
    router: React.PropTypes.object
}

function mapStateToProps(state) {
    const {postsByApi} = state;
    const {
        isFetching,
        items: GoodsInfo
    } = postsByApi["goodsDetail"] || {
        isFetching: false,
        items: {}
    }
    const {
        items: Config
    } = postsByApi["goodsConfig"] || {
        items: {}
    }
    return {
        GoodsInfo,
        Config,
        isFetching
    }
}


export default connect(mapStateToProps)(goodsDetail);

